package com.jwork.progress.controllers;

import com.jwork.progress.config.MinioConfig;
import com.jwork.progress.params.CommonResponse;
import com.jwork.progress.utils.MinioUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Api(tags = "文件管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/oss")
public class UploadController {
    private final MinioUtil minioUtil;
    private final MinioConfig minioConfig;

    @PostMapping("/upload")
    @ApiOperation("提交")
    public CommonResponse uploadReport(MultipartFile file) {
        String filename = file.getOriginalFilename();
        int lastDotIndex = filename.lastIndexOf(".");
        if (lastDotIndex == -1 || lastDotIndex == filename.length() - 1) {
            return CommonResponse.fail("文件不合法！");
        }
        String extension = filename.substring(lastDotIndex + 1);
        String rename = UUID.randomUUID().toString() + "." + extension;

        minioUtil.upload(file, rename);
        Map<String, String> res = new HashMap<>();
        res.put("fileName", rename);
        res.put("url", minioConfig.getUrl());
        res.put("bucket", minioConfig.getBucketName());
        return CommonResponse.success(res);
    }

    @GetMapping("/preview")
    @ApiOperation("预览")
    public CommonResponse preview(String fileName) {
        String fileUrl = minioUtil.getFileUrl(fileName);
        Map<String, String> res = new HashMap<>();
        res.put("fileUrl", fileUrl);
        return CommonResponse.success(res);
    }

    @GetMapping("/download")
    @ApiOperation("下载")
    public void download(String fileName, HttpServletResponse response) {
        minioUtil.download(response, fileName);
    }

    @GetMapping("/downloadMulti")
    @ApiOperation("批量下载")
    public void downloadMulti(String fileNames, HttpServletResponse response) {
        List<String> fileNamesList = Arrays.asList(fileNames.split(","));
        minioUtil.downloadZip(response, fileNamesList);
    }

    @GetMapping("/delete")
    @ApiOperation("删除")
    public CommonResponse delete(String fileName) {
        minioUtil.delete(fileName);
        return CommonResponse.success("成功！");
    }
}
